import { defineStore } from 'pinia'
import { chatCompletion } from '@/services/api'

export const useChatStore = defineStore('chat', {
  state: () => ({
    conversations: [],
    currentConversation: null,
    isLoading: false,
    error: null,
    currentModel: 'deepseek-chat', // 默认模型
    isDarkMode: true, // 默认使用暗色主题
  }),
  
  actions: {
    createNewChat() {
      const conversation = {
        id: Date.now(),
        messages: [],
        title: '新对话'  // 添加标题字段
      }
      // 添加新对话到数组开头
      this.conversations = [conversation, ...this.conversations]
      this.currentConversation = conversation
    },
    
    selectConversation(conversationId) {
      const conversation = this.conversations.find(conv => conv.id === conversationId)
      if (conversation) {
        this.currentConversation = conversation
      }
    },

    // 删除会话
    deleteConversation(conversationId) {
      const index = this.conversations.findIndex(conv => conv.id === conversationId)
      if (index !== -1) {
        this.conversations = this.conversations.filter(conv => conv.id !== conversationId)
        
        // 如果删除的是当前会话，则切换到其他会话
        if (this.currentConversation?.id === conversationId) {
          this.currentConversation = this.conversations[0] || null
        }
      }
    },

    // 更新会话标题
    updateConversationTitle(conversationId, title) {
      const conversation = this.conversations.find(conv => conv.id === conversationId)
      if (conversation) {
        conversation.title = title
        // 触发响应式更新
        this.conversations = [...this.conversations]
      }
    },

    async addMessage(message) {
      if (!this.currentConversation) {
        this.createNewChat()
      }
      
      // 创建新的消息数组引用
      const newMessages = [...this.currentConversation.messages, { ...message }]
      
      // 更新整个会话对象
      this.currentConversation = {
        ...this.currentConversation,
        messages: newMessages
      }

      // 如果是第一条用户消息，使用它作为会话标题
      if (message.role === 'user' && this.currentConversation.messages.length === 1) {
        const title = message.content.slice(0, 20) + (message.content.length > 20 ? '...' : '')
        this.updateConversationTitle(this.currentConversation.id, title)
      }
      
      // 更新会话列表中的对应会话
      const index = this.conversations.findIndex(conv => conv.id === this.currentConversation.id)
      if (index !== -1) {
        this.conversations = [
          ...this.conversations.slice(0, index),
          this.currentConversation,
          ...this.conversations.slice(index + 1)
        ]
      }
      
      if (message.role === 'user') {
        this.isLoading = true
        this.error = null
        
        try {
          const stream = await chatCompletion(this.currentConversation.messages, this.currentModel)
          const reader = stream.getReader()
          const decoder = new TextDecoder('utf-8')
          
          const responseMessage = {
            role: 'assistant',
            content: '',
            timestamp: new Date().toISOString()
          }
          
          // 添加响应消息到对话中
          this.currentConversation = {
            ...this.currentConversation,
            messages: [...this.currentConversation.messages, { ...responseMessage }]
          }
          
          // 同步更新会话列表
          const currentIndex = this.conversations.findIndex(conv => conv.id === this.currentConversation.id)
          if (currentIndex !== -1) {
            this.conversations = [
              ...this.conversations.slice(0, currentIndex),
              this.currentConversation,
              ...this.conversations.slice(currentIndex + 1)
            ]
          }
          
          let buffer = ''
          
          while (true) {
            const { done, value } = await reader.read()
            if (done) break
            
            const chunk = decoder.decode(value, { stream: true })
            buffer += chunk
            
            const lines = buffer.split('\n')
            buffer = lines.pop() || ''
            
            for (const line of lines) {
              if (line.startsWith('data: ')) {
                const data = line.slice(6).trim()
                if (data === '[DONE]') continue
                
                try {
                  const parsed = JSON.parse(data)
                  if (parsed.choices && parsed.choices[0]?.delta?.content) {
                    responseMessage.content += parsed.choices[0].delta.content
                    
                    // 更新整个会话对象以触发响应式更新
                    this.currentConversation = {
                      ...this.currentConversation,
                      messages: this.currentConversation.messages.map(msg => 
                        msg.timestamp === responseMessage.timestamp ? { ...responseMessage } : msg
                      )
                    }
                    
                    // 同步更新会话列表
                    const idx = this.conversations.findIndex(conv => conv.id === this.currentConversation.id)
                    if (idx !== -1) {
                      this.conversations = [
                        ...this.conversations.slice(0, idx),
                        this.currentConversation,
                        ...this.conversations.slice(idx + 1)
                      ]
                    }
                  }
                } catch (e) {
                  console.error('Error parsing SSE data:', e, data)
                }
              }
            }
          }
          
          // 处理剩余的缓冲区
          if (buffer) {
            const lines = buffer.split('\n')
            for (const line of lines) {
              if (line.startsWith('data: ') && !line.includes('[DONE]')) {
                try {
                  const data = line.slice(6).trim()
                  const parsed = JSON.parse(data)
                  if (parsed.choices && parsed.choices[0]?.delta?.content) {
                    responseMessage.content += parsed.choices[0].delta.content
                    
                    // 最后一次更新
                    this.currentConversation = {
                      ...this.currentConversation,
                      messages: this.currentConversation.messages.map(msg => 
                        msg.timestamp === responseMessage.timestamp ? { ...responseMessage } : msg
                      )
                    }
                    
                    // 同步更新会话列表
                    const idx = this.conversations.findIndex(conv => conv.id === this.currentConversation.id)
                    if (idx !== -1) {
                      this.conversations = [
                        ...this.conversations.slice(0, idx),
                        this.currentConversation,
                        ...this.conversations.slice(idx + 1)
                      ]
                    }
                  }
                } catch (e) {
                  console.error('Error parsing final SSE data:', e)
                }
              }
            }
          }
          
        } catch (error) {
          this.error = error.message
          console.error('Failed to get AI response:', error)
        } finally {
          this.isLoading = false
        }
      }
    },

    removeLastMessage() {
      if (this.currentConversation?.messages.length > 0) {
        // 创建新的消息数组，移除最后一条消息
        const newMessages = this.currentConversation.messages.slice(0, -1)
        
        // 更新当前会话
        this.currentConversation = {
          ...this.currentConversation,
          messages: newMessages
        }
        
        // 同步更新会话列表
        const index = this.conversations.findIndex(conv => conv.id === this.currentConversation.id)
        if (index !== -1) {
          this.conversations = [
            ...this.conversations.slice(0, index),
            this.currentConversation,
            ...this.conversations.slice(index + 1)
          ]
        }
      }
    },

    async generateResponse() {
      if (!this.currentConversation) return
      
      try {
        this.isLoading = true
        this.error = null
        
        const messages = [...this.currentConversation.messages]
        const stream = await chatCompletion(messages, this.currentModel)
        const reader = stream.getReader()
        const decoder = new TextDecoder('utf-8')
        
        const responseMessage = {
          role: 'assistant',
          content: '',
          timestamp: new Date().toISOString()
        }
        
        // 如果最后一条是助手消息，先移除它
        const lastMessage = this.currentConversation.messages[this.currentConversation.messages.length - 1]
        if (lastMessage && lastMessage.role === 'assistant') {
          this.currentConversation = {
            ...this.currentConversation,
            messages: this.currentConversation.messages.slice(0, -1)
          }
        }
        
        // 添加新的响应消息
        this.currentConversation = {
          ...this.currentConversation,
          messages: [...this.currentConversation.messages, { ...responseMessage }]
        }
        
        let buffer = ''
        
        while (true) {
          const { done, value } = await reader.read()
          if (done) break
          
          const chunk = decoder.decode(value, { stream: true })
          buffer += chunk
          
          const lines = buffer.split('\n')
          buffer = lines.pop() || ''
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6).trim()
              if (data === '[DONE]') continue
              
              try {
                const parsed = JSON.parse(data)
                if (parsed.choices && parsed.choices[0]?.delta?.content) {
                  responseMessage.content += parsed.choices[0].delta.content
                  
                  // 更新整个会话对象以触发响应式更新
                  this.currentConversation = {
                    ...this.currentConversation,
                    messages: this.currentConversation.messages.map(msg => 
                      msg.timestamp === responseMessage.timestamp ? { ...responseMessage } : msg
                    )
                  }
                }
              } catch (e) {
                console.error('Error parsing SSE data:', e, data)
              }
            }
          }
        }
        
        // 处理剩余的缓冲区
        if (buffer) {
          const lines = buffer.split('\n')
          for (const line of lines) {
            if (line.startsWith('data: ') && !line.includes('[DONE]')) {
              try {
                const data = line.slice(6).trim()
                const parsed = JSON.parse(data)
                if (parsed.choices && parsed.choices[0]?.delta?.content) {
                  responseMessage.content += parsed.choices[0].delta.content
                  
                  // 最后一次更新
                  this.currentConversation = {
                    ...this.currentConversation,
                    messages: this.currentConversation.messages.map(msg => 
                      msg.timestamp === responseMessage.timestamp ? { ...responseMessage } : msg
                    )
                  }
                }
              } catch (e) {
                console.error('Error parsing final SSE data:', e)
              }
            }
          }
        }
        
      } catch (err) {
        this.error = '生成回复失败，请重试'
        console.error('Generate response error:', err)
        throw err
      } finally {
        this.isLoading = false
      }
    },

    switchModel() {
      this.currentModel = this.currentModel === 'deepseek-reasoner' ? 'deepseek-chat' : 'deepseek-reasoner'
    },

    toggleTheme() {
      this.isDarkMode = !this.isDarkMode
      document.documentElement.setAttribute('data-theme', this.isDarkMode ? 'dark' : 'light')
    }
  },
  
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ['conversations', 'currentConversation', 'currentModel', 'isDarkMode']
      }
    ]
  }
}) 